package com.jd.mrd.plugin_jd_passport_login

import android.app.Activity
import android.app.Application
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.jd.mrd.mrdAndroidlogin.Interface.IOneKeyLoginCallback
import com.jd.mrd.mrdAndroidlogin.Interface.IOneKeyLoginPreGetMobileCallback
import com.jd.mrd.mrdAndroidlogin.Interface.OnGetVerifyCodeCallback
import com.jd.mrd.mrdAndroidlogin.Interface.OnPhoneLoginCallback
import com.jd.mrd.mrdAndroidlogin.util.LoginParamConfig
import com.jd.mrd.mrdAndroidlogin.util.LoginUtils
import com.wjlogin.onekey.sdk.model.OneKeyInfo
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import jd.wjlogin_sdk.common.DevelopType
import org.json.JSONException
import org.json.JSONObject


/** PluginJdPassportLoginPlugin */
class PluginJdPassportLoginPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

    private lateinit var applicationContext: Context
    private lateinit var channel: MethodChannel
    private lateinit var result: Result
    private lateinit var activity: Activity

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        applicationContext = binding.applicationContext
        channel = MethodChannel(binding.binaryMessenger, "jdfpassportlogin")
        channel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        LoginUtils.free(activity)
        Log.d("JdfpassportloginPlugin", "onDetachedFromEngine,资源释放了...")
        channel.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        this.result = result

        when (call.method) {
            "init" -> {
                val oneKeyInfo = OneKeyInfo()
                try {
                    val map = call.argument<Map<String, Any>>("onKeyInfo")!!
                    oneKeyInfo.cmAppId = map["cmAppId"] as String?
                    oneKeyInfo.cmAppKey = map["cmAppKey"] as String?
                    oneKeyInfo.cuAppId = map["cuAppId"] as String?
                    oneKeyInfo.cuAppKey = map["cuAppKey"] as String?
                    oneKeyInfo.ctAppId = map["ctAppId"] as String?
                    oneKeyInfo.ctAppKey = map["ctAppKey"] as String?
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                init(
                    call.argument<Any>("appid") as Int,
                    call.argument<Any>("develop") as Int,
                    call.argument<Any>("isLoginSwith") as Boolean,
                    oneKeyInfo
                )
            }
            "loginWithAccountPassword" -> loginWithAccountPassword(
                call.argument<Any>("account") as String,
                call.argument<Any>("password") as String
            )
            "sendVerifyCode" -> sendVerifyCode(call.argument<Any>("phone") as String)
            "loginWithVerifyCode" -> loginWithVerifyCode(
                call.argument<Any>("phone") as String,
                call.argument<Any>("verifycode") as String
            )
            "forgetPassword" -> forgetPassword()
            "loginWithWx" -> loginWithWx(call.argument<Any>("weixinId") as String)
            "loginWithJD" -> loginWithJD()
            "oneKeyLoginPreGetMobile" -> oneKeyLoginPreGetMobile()
            "oneKeyLoginWithOperator" -> oneKeyLoginWithOperator(call.argument<Any>("securityPhone") as String)
            "getAppVersion" -> getAppVersion()
            else -> result.notImplemented()
        }
    }

    /**
     * 获取APP版本号
     */
    private fun getAppVersion() {
        val versionName =
            activity.packageManager.getPackageInfo(activity.packageName, 0).versionName
        result.success(versionName)
    }

    /**
     * 账号密码登录
     *
     * @param account
     * @param sUserPassword
     */
    private fun loginWithAccountPassword(account: String, sUserPassword: String) {
        LoginUtils.accountPasswordLogin(
            activity,
            account,
            sUserPassword,
            object : OnPhoneLoginCallback {
                override fun OnPhoneLoginSuccess() {
                    result.success(getUserInfo())
                }

                override fun OnPhoneLoginFail(failMsg: String) {
                    result.error("loginFail", failMsg, null)
                }
            })
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    private fun sendVerifyCode(phone: String) {
        LoginUtils.getVerifyCode(activity, phone, object : OnGetVerifyCodeCallback {
            override fun onSuccess(mMsgCodeExpireTime: Int) {
                result.success(mMsgCodeExpireTime)
            }

            override fun onfail(error: String) {
                result.error("sendVerifyCodeFail", error, null)
            }
        })
    }

    /**
     * 手机验证码登录
     */
    private fun loginWithVerifyCode(phone: String, verifyCode: String) {
        LoginUtils.phoneVerifyCodeLogin(activity, phone, verifyCode, object : OnPhoneLoginCallback {
            override fun OnPhoneLoginSuccess() {
                result.success(getUserInfo())
            }

            override fun OnPhoneLoginFail(failMsg: String) {
                result.error("loginFail", failMsg, null)
            }
        })
    }

    /**
     * 忘记密码
     */
    private fun forgetPassword() {
        LoginUtils.forgetPassword(activity)
    }

    /**
     * 微信登录
     *
     * @param weixinId
     */
    private fun loginWithWx(weixinId: String) {
        LoginUtils.weixinThirdLogin(activity, weixinId, object : OnPhoneLoginCallback {
            override fun OnPhoneLoginSuccess() {
                result.success(getUserInfo())
            }

            override fun OnPhoneLoginFail(failMsg: String) {
                Log.e("TAD", "=====loginWithWx,failMsg:$failMsg")
                result.error("loginFail", failMsg, null)
            }
        })
    }

    /**
     * 京东登录
     */
    private fun loginWithJD() {
        LoginUtils.jdThirdLogin(activity, object : OnPhoneLoginCallback {
            override fun OnPhoneLoginSuccess() {
                result.success(getUserInfo())
            }

            override fun OnPhoneLoginFail(failMsg: String) {
                result.error("loginFail", failMsg, null)
            }
        })
    }

    /**
     * 预取号：调用一键登录SDK方法获取安全手机号
     *
     * 说明：这个方法可以获取到手机号，用在一键登录页面展示手机号码。在app启动时调用，尽量靠前，否则可能进入登录页面后没有返回数据会导致页面无法展示手机号。
     */
    private fun oneKeyLoginPreGetMobile() {
        LoginUtils.oneKeyLoginPreGetMobile(object : IOneKeyLoginPreGetMobileCallback {
            override fun onPreGetMobileSuccess(phone: String) {
                Log.e(
                    "wei",
                    "======oneKeyLoginPreGetMobile=====Thread.currentThread().getName():" + Thread.currentThread().name
                )
                activity.runOnUiThread { result.success(phone) }
            }

            override fun onPreGetMobileFail(s: String) {
                result.error("loginFail", s, null)
            }
        })
    }

    /**
     * 运营商一键登录
     *
     * @param securityPhone 一键登录SDK方法获取的安全手机号
     *
     *
     * 【注意】：调用一键登录前，确保调用 oneKeyLoginPreGetMobile() ，且成功取到securityPhone
     */
    private fun oneKeyLoginWithOperator(securityPhone: String) {
        if (TextUtils.isEmpty(securityPhone)) {
            result.error(
                "loginFail",
                "securityPhone 不能为null,确保 call oneKeyLoginPreGetMobile 获取手机号",
                null
            )
            return
        }
        LoginUtils.getOneKeyLoginccessToken(activity, securityPhone, object : IOneKeyLoginCallback {
            override fun onStart() {}
            override fun onLoginSuccess() {
                activity.runOnUiThread { result.success(getUserInfo()) }
            }

            override fun onLoginFail(s: String) {
                result.error("loginFail", s, null)
            }

            override fun onComplied() {}
        })
    }

    private fun init(appid: Int, develop: Int, isLoginSwith: Boolean, oneKeyInfo: OneKeyInfo) {
        val loginParamConfig = LoginParamConfig.Builder()
            .setDevelopType(getDevelopType(develop)) //环境
            .setAppid(appid.toShort()) //appid
            .setLogintSwitch(isLoginSwith)
            .setOneKeyInfo(oneKeyInfo)
            //.setAppName("appName")
            //.setChnAppName("app中文名称")
            .build()
        LoginUtils.init(applicationContext as Application, loginParamConfig)
    }

    private fun getDevelopType(develop: Int): Int {
        return when (develop) {
            0 -> DevelopType.PRODUCT
            1 -> DevelopType.DEBUG
            2 -> DevelopType.BETA
            else -> DevelopType.PRODUCT
        }
    }


    /**
     * 获取pin /a2
     *
     * @return
     */
    private fun getUserInfo(): String {
        val jsonInfo = JSONObject()
        try {
            jsonInfo.put("pin", LoginUtils.getHelper(activity.application).pin)
            jsonInfo.put("a2", LoginUtils.getHelper(activity.application).a2)
            jsonInfo.put("account", LoginUtils.getHelper(activity.application).userAccount)
            Log.d("JdfpassportloginPlugin", "object.toString:$jsonInfo")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonInfo.toString()
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {}

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {}

    override fun onDetachedFromActivity() {}
}
